let util = require('../../../util/util.js');
let wechat = require("../../../util/wechat");
let amap = require("../../../util/amap");
Page({
  data: {
    lonlat: "",
    city: "",
    tips: [],
    hotList: [],
    showHot: true
  },
  onLoad(e) {
    console.log(e);
    let { lonlat, city } = e;
    this.setData({
      lonlat, city
    });
    this.loadHotList();
  },
  loadHotList() {
    wx.cloud.database().collection('zyzl_nearbylist')
      .orderBy('eva', 'desc')
      .limit(10)
      .get()
      .then(res => {
        this.setData({
          hotList: res.data
        });
      })
      .catch(err => {
        console.error('获取热门推荐失败：', err);
      });
  },
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/nearby/nearbydetail/nearbydetail?id=${id}&type=nearby`
    });
  },
  onSearchFocus() {
    this.setData({
      showHot: false
    });
  },
  onSearchBlur(e) {
    if (!e.detail.value) {
      this.setData({
        showHot: true
      });
    }
  },
  bindInput(e) {
    let { value } = e.detail;
    let { lonlat, city } = this.data;

    if (!value) {
      this.setData({
        showHot: true,
        tips: []
      });
      return;
    }

    amap.getInputtips(city, lonlat, value)
      .then(d => {
        if (d && d.tips) {
          this.setData({
            tips: d.tips,
            showHot: false
          });
        }
      })
      .catch(e => {
        console.log(e);
      })
  },
  bindSearch(e) {
    console.log(e);
    let { keywords } = e.target.dataset;
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];  
    if (keywords) {
      prevPage.setData({ keywords });
      amap.getPoiAround(keywords)
        .then(d => {
          let { markers } = d;
          markers.forEach(item => {
            item.iconPath = "../images/Bluemaker.png";
          })
          prevPage.setData({ markers });
          prevPage.showMarkerInfo(markers[0]);
          prevPage.changeMarkerColor(0);
        })
        .catch(e => {
          console.log(e);
        })
    }
    let url = `/pages/map/index/index`;
    wx.switchTab({ url })
  }
});
